/**
 * 加载中ing
 * @returns
 */
function showLoading() {
	$('body').loading({
		loadingWidth:120,
		title:'',
		name:'loadingMan',
		discription:'',
		direction:'column',
		type:'origin',
		// originBg:'#71EA71',
		originDivWidth:40,
		originDivHeight:40,
		originWidth:6,
		originHeight:6,
		smallLoading:false,
		loadingMaskBg:'rgba(0,0,0,0.2)'
	});
}

/**
 * 移除加载中ing
 * @returns
 */
function hideLoading(){
	removeLoading('loadingMan');
}

/**
 * 检查response访问是否成功
 * @param response
 * @returns
 */
function checkStatus(response) {
	if (response.status >= 200 && response.status < 300) {
		return response;
	} else {
		let error = new Error(response.statusText)
		error.response = response;
		throw error;
	}
}

/**
 * response转json
 * @param response
 * @returns
 */
function parseJSON(response) {
	return response.json();
}

/**
 * json转url参数
 * @param param
 * @param key
 * @returns
 */
function parseParam(param, key) {
    let paramStr = "";
    let paramtype = typeof(param);
    if (paramtype === 'string' || paramtype === 'number' || paramtype === 'boolean') {
        paramStr += "&" + key + "=" + encodeURIComponent(param);
    } else {
    	for(let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + parseParam(param[i], k);
        }
    }
    return paramStr.substr(1);
};

/**
 * json转formData
 * @param formData
 * @param param
 * @param key
 * @returns
 */
function parseFormData(formData, param, key) {
    let paramtype = typeof(param);
    if (paramtype === 'string' || paramtype === 'number' || paramtype === 'boolean') {
		formData.append(key, param);
    } else {
    	for(let i in param) {
            let k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            formData = parseFormData(formData, param[i], k);
        }
    }
	return formData;
}

/**
 * get访问
 */
function get(url, success, data, error){
	if(typeof(url)==="undefined" && url===null && url===''){
		return false;
	}
	if(data!==null && typeof(data)==='object'){
		url += "?"+parseParam(data);
	}
	fetchRequest('GET', url, success, null, error);
}

/**
 * post提交请求
 */
function post(url, success, data, error){
	if(typeof(url)==="undefined" && url===null && url===''){
		return false;
	}
	if(!(data instanceof FormData) && data!==null && typeof(data)==='object'){
		data = parseFormData(new FormData(), data);
	}
	fetchRequest('POST', url, success, data, error);
}

/**
 * put提交请求参数是一个对象
 */
function put(url, success, data, error){
	if(typeof(url)==="undefined" && url===null && url===''){
		return false;
	}
	if(data!==null && typeof(data)==='object'){
		data = JSON.stringify(data);
	}
	fetchRequest('PUT', url, success, data, error, 'application/json');
}

/**
 * 提交删除请求
 */
function del(url, success, error){
	if(typeof(url)==="undefined" && url===null && url===''){
		return false;
	}
	fetchRequest('DELETE', url, success, null, error);
}

/**
 * fetch请求
 */
function fetchRequest(method, url, success, data, error, contentType){
	if(typeof(url)==="undefined" && url===null && url===''){
		return false;
	}
	
	if(typeof(method)==="undefined" && method===null && method===''){
		return false;
	}
	
	method = method.toUpperCase();//转成全大写
	
	let requestData = {
		method: method,
		//credentials: 'same-origin' //同域中自动发送cookie,加上 credentials 的 same-origin选项。否则，Cookie将不会被发送，导致这些请求不保留认证会话。
		credentials: 'include' //对于CORS请求，使用include值允许将凭据发送到其他域 
	};
	
	if(typeof(data)!=="undefined" && data!==null){
		requestData['body'] = data;
	}
	
	if(typeof(contentType)!=="undefined" && contentType!==null){
		requestData['headers'] = {'Content-Type': contentType};
	}
	
	showLoading();
	
	fetch(url, requestData)
	.then(checkStatus)
	.then(parseJSON)
	.then(function(obj) {
		hideLoading();
		console.log(url, requestData, obj);
		if(success instanceof Function){
			success(obj);
		}
	}).catch(function(e) {
		hideLoading();
		console.log(url, requestData, e);
		spop(e, 'error');
		if(error instanceof Function){
			error(e);
		}
	});
}